package com.android.djlmapp.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.djlmapp.R;
import com.android.djlmapp.activity.home.ChooseActivity;
import com.android.djlmapp.activity.home.GongGaoListActivity;
import com.android.djlmapp.activity.home.SaveCodeActivity;
import com.android.djlmapp.activity.home.web.BukaActivity;
import com.android.djlmapp.activity.home.web.BuyPhoneActivity;
import com.android.djlmapp.activity.home.web.DayPriceActivity;
import com.android.djlmapp.activity.home.web.DianXinActivity;
import com.android.djlmapp.activity.home.web.GongHuoShangActivity;
import com.android.djlmapp.activity.home.web.MoreFunActivity;
import com.android.djlmapp.activity.home.web.PaiHangBangActivity;
import com.android.djlmapp.activity.home.web.RechargeActivity;
import com.android.djlmapp.activity.home.web.ZxingWebActivity;
import com.android.djlmapp.activity.home.web.base.BaseWebActivity;
import com.android.djlmapp.activity.home.web.base.ResetCardActivity;
import com.android.djlmapp.activity.kaika.BarCodeScanerActivity;
import com.android.djlmapp.activity.kaika.KaiKaActivity;
import com.android.djlmapp.activity.kuandai.KuanDaiActivity;
import com.android.djlmapp.adapter.home.HomeGrideAdapter;
import com.android.djlmapp.adapter.msg.MsgListActivity;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.base.BaseFragment;
import com.android.djlmapp.dialog.GongGaoDialog;
import com.android.djlmapp.http.ComPareUtils;
import com.android.djlmapp.http.GlobalUrls;
import com.android.djlmapp.model.home.DjlmInfo;
import com.android.djlmapp.model.home.HomeFragmentInfo;
import com.android.djlmapp.model.readcard.CardDataInfo;
import com.android.djlmapp.token.GetUrlStr;
import com.android.djlmapp.tools.global.ConstantsValue;
import com.android.djlmapp.tools.global.PrefUtils;
import com.android.djlmapp.tools.global.ToastUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.view.NoScrollGridView;
import com.android.djlmapp.view.WebView4Scroll;
import com.android.readcard.global.PrefReadCardTools;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.android.djlmapp.activity.home.web.base.BaseWebActivity.PAGE_URL_KEY;
import static com.android.djlmapp.http.GlobalUrls.BROADBAND_PURPOSE_BILL_URL;
import static com.android.djlmapp.http.GlobalUrls.BUKA_URL;
import static com.android.djlmapp.http.GlobalUrls.PHONERECHANGE_ACTIVITY;
import static com.android.djlmapp.http.GlobalUrls.QQ_CZ;
import static com.android.djlmapp.http.GlobalUrls.TAB_HOME_MORE_FUNCTION;
import static com.android.djlmapp.http.GlobalUrls.USER_VERIFY_URL;

public class ShouYeFragment extends BaseFragment {

    @BindView(R.id.iv_ph_photo1)
    ImageView ivPhPhoto1;
    @BindView(R.id.tv_ph_num1)
    TextView tvPhNum1;
    @BindView(R.id.iv_ph_photo2)
    ImageView ivPhPhoto2;
    @BindView(R.id.tv_ph_num2)
    TextView tvPhNum2;
    @BindView(R.id.iv_ph_photo3)
    ImageView ivPhPhoto3;
    @BindView(R.id.tv_ph_num3)
    TextView tvPhNum3;
    Unbinder unbinder;
    @BindView(R.id.rl_ph1)
    RelativeLayout rlPh1;
    @BindView(R.id.rl_ph2)
    RelativeLayout rlPh2;
    @BindView(R.id.rl_ph3)
    RelativeLayout rlPh3;
    @BindView(R.id.rl_go_ph)
    RelativeLayout rlGoPh;
    @BindView(R.id.tv_ph_mobile1)
    TextView tvPhMobile1;
    @BindView(R.id.tv_ph_address1)
    TextView tvPhAddress1;
    @BindView(R.id.tv_ph_mobile2)
    TextView tvPhMobile2;
    @BindView(R.id.tv_ph_address2)
    TextView tvPhAddress2;
    @BindView(R.id.tv_ph_mobile3)
    TextView tvPhMobile3;
    @BindView(R.id.tv_ph_address3)
    TextView tvPhAddress3;
    @BindView(R.id.ll_top_back)
    LinearLayout llTopBack;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.iv_top_msg)
    ConstraintLayout ivTopMsg;
    @BindView(R.id.home_iv_readpoint)
    ImageView ivRedPoint;
    @BindView(R.id.iv_top_set)
    ImageView ivTopSet;
    @BindView(R.id.iv_top_kf)
    ImageView ivTopKf;
    @BindView(R.id.page_title_layout)
    ConstraintLayout pageTitleLayout;
    @BindView(R.id.webviewframe)
    WebView webviewframe;
    @BindView(R.id.iv_user_photo)
    ImageView ivUserPhoto;
    @BindView(R.id.iv_star)
    ImageView ivStar;
    @BindView(R.id.rl_photo)
    RelativeLayout rlPhoto;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_user_hone)
    TextView tvUserHone;
    @BindView(R.id.ll_user_info)
    LinearLayout llUserInfo;
    @BindView(R.id.ll_paihang)
    LinearLayout llPaihang;
    @BindView(R.id.ll_new_msg)
    LinearLayout llNewMsg;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.iv_sys)
    ImageView ivSys;
    @BindView(R.id.gv_function)
    NoScrollGridView gvFunction;
    @BindView(R.id.iv_new)
    ImageView ivNew;
    @BindView(R.id.tv_msg1)
    TextView tvMsg1;
    @BindView(R.id.tv_time1)
    TextView tvTime1;
    @BindView(R.id.rl_msg1)
    RelativeLayout rlMsg1;
    @BindView(R.id.tv_msg2)
    TextView tvMsg2;
    @BindView(R.id.tv_time2)
    TextView tvTime2;
    @BindView(R.id.rl_msg2)
    RelativeLayout rlMsg2;
    @BindView(R.id.iv_go_ph)
    ImageView ivGoPh;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.refresh)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.title_line)
    View titleLine;

    private ArrayList<HomeFragmentInfo.ActionListBean> mList = new ArrayList<HomeFragmentInfo.ActionListBean>();
    private HomeGrideAdapter homeGrideAdapter;

    private String userImg = "";
    private String phMobile;
    private String phRegionName;
    private String phOrderCount;

    private String userImg1 = "";
    private String phMobile1;
    private String phRegionName1;
    private String phOrderCount1;

    private String userImg2 = "";
    private String phMobile2;
    private String phRegionName2;
    private String phOrderCount2;

    public AgentWeb mAgentWeb;
    private AgentWeb.PreAgentWeb mPreAgentWeb;
    private WebView4Scroll webView4Scroll;
    private static final int REQUEST_CODE = 100;

    private boolean isHaveData = false; // 设置按钮的集合是否有数据
    private String my_qrcode;

    public static ShouYeFragment newInstance(String tabName) {
        ShouYeFragment homeFragment = new ShouYeFragment();
        homeFragment.tag = tabName;
        return homeFragment;
    }

    private static final String[] icons = new String[]{"home_hmkk.png", "home_hfcz.png",
            "home_kdrh.png", "home_gmsj.png", "home_bkhk.png", "home_fkcz.png", "home_tcqz.png",
            "home_qqcz.png", "home_pdyw.png", "home_kdyxd.png", "home_yhyz.png", "home_gdgn.png"};

    private static final String[] names = new String[]{"号码开卡", "话费充值", "宽带融合", "购买手机",
            "补卡换卡", "废卡重置", "套餐迁转", "QQ充值", "派单业务", "宽带意向单", "用户验证", "更多功能"};

    private static final String[] actions = new String[]{"hmkk", "hfcz", "kdrh", "gmsj", "bkhk",
            "fkcz", "tcqz", "qqcz", "pdyw", "kdyxd", "yhyz", "gdgn"};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.fragment_home, container, false);

        unbinder = ButterKnife.bind(this, fragmentView);
        initView();
        return fragmentView;
    }


    @Override
    public void initView() {
        llTopBack.setVisibility(View.GONE);
        ivTopMsg.setVisibility(View.VISIBLE);
        ivTopSet.setVisibility(View.GONE);
        ivTopKf.setVisibility(View.GONE);
        titleLine.setVisibility(View.GONE);
        tvName.setText("店家联盟");
        isHaveData = false;
//        initWeb(); // 初始化web

        llPaihang.setVisibility(View.GONE); // 默认隐藏排行布局
        llNewMsg.setVisibility(View.GONE); // 默认隐藏最新消息布局

        mList = new ArrayList<HomeFragmentInfo.ActionListBean>();


        for (int i = 0; i < icons.length; i++) {
            HomeFragmentInfo.ActionListBean actionListBean = new HomeFragmentInfo.ActionListBean();
            actionListBean.setAction(actions[i]);
            actionListBean.setName(names[i]);
            actionListBean.setIcon(GlobalUrls.MAIN_URL + icons[i]);
            mList.add(actionListBean);
        }

        // 如果集合长度为0,则添加图标
        homeGrideAdapter = new HomeGrideAdapter(_mActivity);
        homeGrideAdapter.setData(mList, isHaveData);
        gvFunction.setAdapter(homeGrideAdapter);

        swipeRefreshLayout.setColorSchemeResources(R.color.homeBule);

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadWeb();
                initData();
//                webviewframe.reload();
            }
        });

        gvFunction.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if ((mList != null && mList.size() > 0) || actions.length > 0) {
                    String action = "";
                    if (isHaveData) {
                        action = mList.get(position).getAction();
                    } else {
                        action = actions[position];
                    }

                    homeJumpActivity(action);
                }
            }
        });
    }

    private void homeJumpActivity(String action) {
        String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
        String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
        String sign = new ComPareUtils.ComPareBuilder()
                .put("token", token)
                .put("version", version)
                .create()
                .getSignString();

        switch (action) {
            case ConstantsValue.HMKK:
                // 号码开卡
                startActivity(new Intent(_mActivity, KaiKaActivity.class));
                break;
            case ConstantsValue.HFCZ:
                // 话费充值
//                            startActivity(new Intent(_mActivity, SelectNumActivity.class));
                String requestUrlTel = PHONERECHANGE_ACTIVITY + "?token=" + token + "&version=" + version + "&sign=" + sign;
                Intent intentTel = new Intent(_mActivity, RechargeActivity.class);
                intentTel.putExtra(PAGE_URL_KEY, requestUrlTel);
                startActivity(intentTel);

                break;
            case ConstantsValue.KDRH:
                // 宽带融合
                startActivity(new Intent(_mActivity, KuanDaiActivity.class));
                break;
            case ConstantsValue.GMSJ:
                // 购买手机
                startActivity(new Intent(_mActivity, BuyPhoneActivity.class));

                break;
            case ConstantsValue.FKCZ:
                // 废卡重置
                startActivity(new Intent(_mActivity, ResetCardActivity.class));

                break;
            case ConstantsValue.BKHK:
                // 补卡换卡
                Intent bkIntent = new Intent(_mActivity, BukaActivity.class);
                bkIntent.putExtra(PAGE_URL_KEY, BUKA_URL + "?token=" + token + "&version=" + version + "&sign=" + sign);
                startActivity(bkIntent);

                break;
            case ConstantsValue.TCQZ:
                // 套餐迁移
                new AlertDialog.Builder(_mActivity)
                        .setPositiveButton("确定", ((dialog, which) -> dialog.cancel()))
                        .setCancelable(false)
                        .setMessage("当前地区暂未开放!")
                        .show();
                break;
            case ConstantsValue.YHYZ:
                // 用户验证
                String requestVerify = USER_VERIFY_URL + "?token=" + token + "&version=" + version + "&sign=" + sign;
                Intent intentVerify = new Intent(_mActivity, BaseWebActivity.class);
                intentVerify.putExtra(PAGE_URL_KEY, requestVerify);
                startActivity(intentVerify);

                break;
            case ConstantsValue.QQCZ:
                // QQ充值
                String requestUrlQQ = QQ_CZ + "?token=" + token + "&version=" + version + "&sign=" + sign;
                Intent intentQQ = new Intent(_mActivity, RechargeActivity.class);
                intentQQ.putExtra(PAGE_URL_KEY, requestUrlQQ);
                startActivity(intentQQ);

                break;
            case ConstantsValue.KDYX:
                // 宽带意向单
                String requestUrlBB = BROADBAND_PURPOSE_BILL_URL + "?token=" + token + "&version=" + version + "&sign=" + sign;
                Intent intentBB = new Intent(_mActivity, BaseWebActivity.class);
                intentBB.putExtra(PAGE_URL_KEY, requestUrlBB);
                startActivity(intentBB);

                break;
            case ConstantsValue.GDGN:
                // 更多功能
                String requestUrlMore = TAB_HOME_MORE_FUNCTION + "?token=" + token + "&version=" + version + "&sign=" + sign;
                Intent intentMore = new Intent(_mActivity, MoreFunActivity.class);
                intentMore.putExtra(PAGE_URL_KEY, requestUrlMore);
                startActivity(intentMore);
                break;
            default:
                break;
        }
    }

    private void initWeb() {
        WebSettings webSettings = webviewframe.getSettings();
        webviewframe.setWebViewClient(mWebViewClient);
        scrollView.scrollTo(0, 0);
        scrollView.smoothScrollTo(0, 0);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDefaultTextEncodingName("utg-8");
        webSettings.setJavaScriptEnabled(true);
    }

    @Override
    public void initData() {
        getHomeData(); // 获取首页数据
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        loadWeb();
        initData();
    }

    /**
     * 当一个 Activity 中包含多个 Fragment 时,通过选择器切换Fragment 不会调用 onResume(),只会调用 onHiddenChanged()
     */
//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        Log.e("项目异常onLazyInitView", "------onHiddenChanged------" + hidden);
//        if (!hidden) {
//            loadWeb();
//        }
//    }
    private void getHomeData() {
        MyApplication.getInstance().getHttpTools().getHomeData(mHOmeStringCallback);
    }

    private void getReadCardData() {
        MyApplication.getInstance().getHttpTools().getReadCardData(mReadStringCallback);
    }

    private void getDjlmReadCardData() {
        MyApplication.getInstance().getHttpTools().getDjlmReadCardData(mDjlmReadStringCallback);
    }

    private void loadWeb() {
        initWeb();
        String signUrl = new ComPareUtils.ComPareBuilder()
                .put("token", getToken())
                .put("version", getVersion())
                .create().getSignString();

        String url = GlobalUrls.NEW_HOME_PHONE_URL +
                "?token=" + getToken() + "&version=" +
                getVersion() + "&sign=" + signUrl;
        webviewframe.loadUrl(url);

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int w = View.MeasureSpec.makeMeasureSpec(0,
                            View.MeasureSpec.UNSPECIFIED);
                    int h = View.MeasureSpec.makeMeasureSpec(0,
                            View.MeasureSpec.UNSPECIFIED);
                    //重新测量
//            webView4Scroll.measure(w, h);
                    webviewframe.measure(w, h);
                    break;
                case 2:
                    Log.e("首页数据加载", "--------getHomeData----" + isHOmeData);
                    if (!isHOmeData) {
                        getHomeData();
                    }
                    break;
            }
        }
    };
    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.e("项目异常TestWebInterface", "------shouldOverrideUrlLoading11------" + url);
            if (url.contains("login_out")) {
                GetUrlStr.getStrUrl(_mActivity);
                return true;
            } else if (url.contains("/terminal/index")) {
                startActivity(new Intent(_mActivity, BuyPhoneActivity.class));
                return true;
            } else if (url.contains(GlobalUrls.MAIN_URL + "/app5/terminal/new_mobile/mobile_id/")) {

                String[] mobiles = url.split("mobile_id/");
                String[] split = mobiles[1].split("/token/");
                String mobileid = split[0];
                Intent intent = new Intent(_mActivity, GongHuoShangActivity.class);
                intent.putExtra("mobile_id", mobileid.trim());
                intent.putExtra("ghsList", "ghsList");
                startActivity(intent);
                return true;
            } else if (url.contains("day_price")) {
                startActivity(new Intent(_mActivity, DayPriceActivity.class));
                return true;
            } else {
                return false;
            }
        }

        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            Log.e("项目异常TestWebInterface", "------shouldOverrideUrlLoading2222------" + url);
            if (url.contains("login_out")) {
                GetUrlStr.getStrUrl(_mActivity);
                return true;
            } else if (url.contains("/terminal/index")) {
                startActivity(new Intent(_mActivity, BuyPhoneActivity.class));
                return true;
            } else if (url.contains(GlobalUrls.MAIN_URL + "/app5/terminal/new_mobile/mobile_id/")) {

                String[] mobiles = url.split("mobile_id/");
                String[] split = mobiles[1].split("/token/");
                String mobileid = split[0];
                Intent intent = new Intent(_mActivity, GongHuoShangActivity.class);
                intent.putExtra("mobile_id", mobileid.trim());
                intent.putExtra("ghsList", "ghsList");
                startActivity(intent);
                return true;
            } else if (url.contains("day_price")) {
                startActivity(new Intent(_mActivity, DayPriceActivity.class));
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            Log.e("项目异常onLazyInitView", mList.size() + "------onPageFinished------" + url);
            // 解决ScrollView嵌套WebView时出现大面积空白或者加载成功不显示的问题
            mHandler.sendEmptyMessage(1);
            mHandler.sendEmptyMessageDelayed(2, 500);
        }
    };

    @OnClick({R.id.iv_top_msg, R.id.iv_code, R.id.iv_sys, R.id.ll_new_msg, R.id.rl_go_ph})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_top_msg: // 消息
                startActivity(new Intent(_mActivity, MsgListActivity.class));
                break;
            case R.id.iv_code: // 二维码
                startActivity(new Intent(_mActivity, SaveCodeActivity.class).putExtra("CODEURL", my_qrcode));
                break;
            case R.id.iv_sys: // 扫一扫
                startActivityForResult(new Intent(_mActivity, BarCodeScanerActivity.class), REQUEST_CODE);
                _mActivity.overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
                break;
            case R.id.ll_new_msg: // 跳转最新消息
                startActivity(new Intent(_mActivity, GongGaoListActivity.class));
                break;
            case R.id.rl_go_ph: // 跳转排行
                startActivity(new Intent(_mActivity, PaiHangBangActivity.class));
                break;
        }
    }

    private boolean isHOmeData = false;
    private StringCallback mHOmeStringCallback = new StringCallback() {

        @Override
        public void onSuccess(Response<String> response) {
            Log.e("项目异常onLazyInitView", "------mHOmeStringCallback------");
            try {
                String body = response.body();
                parseHomeJson(body);
            } catch (Exception e) {
                llPaihang.setVisibility(View.GONE);
                llNewMsg.setVisibility(View.GONE);
                ToastUtils.showShortToast(_mActivity, "数据解析异常one");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            llPaihang.setVisibility(View.GONE);
            llNewMsg.setVisibility(View.GONE);
            Log.e("首页数据", response.code() + "-----onError------" + response.getException());
            ToastUtils.showShortToast(_mActivity, "网络或服务器错误");
        }

        @Override
        public void onFinish() {
            super.onFinish();
            isLoad = true;
            isHOmeData = true;
            if (!isReadData) {
                getReadCardData(); // 获取读卡数据

            }
            if (swipeRefreshLayout.isRefreshing()) {
                swipeRefreshLayout.postDelayed(() -> swipeRefreshLayout.setRefreshing(false), 300);
            }
        }
    };
    private boolean isReadData = false;
    private StringCallback mReadStringCallback = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            Log.e("项目异常onLazyInitView", "------mReadStringCallback------");
            try {
                String body = response.body();
                parseReadJson(body);
            } catch (Exception e) {
                ToastUtils.showShortToast(_mActivity, "数据解析异常two");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            String body = response.body();
            Log.e("首页数据", "-----onError------" + body);
            ToastUtils.showShortToast(_mActivity, "网络或服务器错误two");
        }

        @Override
        public void onFinish() {
            super.onFinish();
            isReadData = true;
            Log.e("首页数据加载", "-------getDjlmReadCardData----" + isDjlmRead);
            if (!isDjlmRead) {
                getDjlmReadCardData();
            }
        }
    };
    private boolean isDjlmRead = false;
    private StringCallback mDjlmReadStringCallback = new StringCallback() {
        @Override
        public void onSuccess(Response<String> response) {
            Log.e("项目异常onLazyInitView", "------mDjlmReadStringCallback------");
            try {
                String body = response.body();
                parseDjlmReadJson(body);
            } catch (Exception e) {
                ToastUtils.showShortToast(_mActivity, "数据解析异常three");
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            String body = response.body();
            Log.e("首页数据", "-----onError------" + body);
            ToastUtils.showShortToast(_mActivity, "网络或服务器错误three");
        }

        @Override
        public void onFinish() {
            super.onFinish();
            isDjlmRead = true;
        }
    };

    private void parseDjlmReadJson(String body) {
        Gson gson = new Gson();
        DjlmInfo djlmInfo = gson.fromJson(body, DjlmInfo.class);
        if (djlmInfo != null) {
            if (djlmInfo.getCode() < 1000) {
                String djlmUrl = djlmInfo.getUrl();
                String djlmIp = djlmInfo.getIp();
                String djlmNewUrl = djlmInfo.getUrl_new();
                if (!TextUtils.isEmpty(djlmUrl) && !TextUtils.isEmpty(djlmIp) && !TextUtils.isEmpty(djlmNewUrl)) {
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.DJLM_IP, djlmIp);
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.DJLM_URL, djlmUrl);
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.DJLM_NEW_URL, djlmNewUrl);
                } else {
//                    ToastUtils.showShortToast(_mActivity, "服务器返回IP地址为空");
                }
            } else {
//                ToastUtils.showShortToast(_mActivity, djlmInfo.getMsg());
            }
        } else {
//            ToastUtils.showShortToast(_mActivity, "服务器返回数据为空");
        }
    }

    private void parseReadJson(String s) {
        Gson gson = new Gson();
        CardDataInfo cardDataInfo = gson.fromJson(s, CardDataInfo.class);
        if (cardDataInfo != null) {
            if (cardDataInfo.getCode() < 1000) {
                CardDataInfo.ConfigBean.ANDROIDBean android = cardDataInfo.getConfig().getANDROID();
                if (android != null) {
                    // 恒鸿达
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.HHDserverIp, android.getHHD().getServerIp());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.HHDaccount, android.getHHD().getAccount());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.HHDport, android.getHHD().getPort());

                    // 卡尔分体
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.KRFTserverIp, android.getKRFT().getServerIp());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.KRFTaccount, android.getKRFT().getAccount());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.KRFTpassword, android.getKRFT().getPassword());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.KRFTport, android.getKRFT().getPort());

                    // OTG
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.OTGserverIp, android.getOTG().getServerIp());

                    // 森锐
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.SRserverIp, android.getSR().getServerIp());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.SRaccount, android.getSR().getAccount());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.SRpassword, android.getSR().getPassword());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.SRport, android.getSR().getPort());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.SRkey, android.getSR().getKey());

                    // 华视
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.HSkey, android.getHS().getKey());

                    // 信通
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.XTserverIp, android.getXT().getServerIp());
                    PrefReadCardTools.setString(_mActivity, ConstantsValue.XTport, android.getXT().getPort());

                }
            } else {
                Log.e("首页数据", "------getReadIp--onError----" + cardDataInfo.getMsg());
            }
        }
    }

    private void parseHomeJson(String s) {
        Gson gson = new Gson();
        HomeFragmentInfo homeFragmentInfo = gson.fromJson(s, HomeFragmentInfo.class);
        if (homeFragmentInfo != null) {
            int code = homeFragmentInfo.getCode();
            if (code < 1000) {
                PrefUtils.putString(ConstantsValue.BD_MOBILE, homeFragmentInfo.getUser_info().getMobile());
                // 显示公告
                String alert_notice = homeFragmentInfo.getAlert_notice();
                if (!TextUtils.isEmpty(alert_notice) && alert_notice != null) {
                    GongGaoDialog dialog = new GongGaoDialog(_mActivity, alert_notice);
                    dialog.show();
                }
                my_qrcode = homeFragmentInfo.getMy_qrcode();
                if (!TextUtils.isEmpty(my_qrcode)) {
                    ivCode.setVisibility(View.VISIBLE);
                } else {
                    ivCode.setVisibility(View.GONE);
                }
                saveSrValue(homeFragmentInfo); // 保存森锐串码
                setPhoto(homeFragmentInfo); // 设置头像
                setHomeButton(homeFragmentInfo); // 设置首页功能按钮
                setNewMsg(homeFragmentInfo); // 设置最新消息
                setPaiHangData(homeFragmentInfo); // 设置排行榜数据
                setRedPoint(homeFragmentInfo); // 设置小红点显示
            } else {
                ToastUtils.showShortToast(_mActivity, homeFragmentInfo.getMsg());
            }
        } else {
            ToastUtils.showShortToast(_mActivity, "未获取到数据");
        }
    }

    private void setRedPoint(HomeFragmentInfo homeFragmentInfo) {
        String no_read_msg = homeFragmentInfo.getNo_read_msg();
        String no_read_mail = homeFragmentInfo.getNo_read_mail();
        if (!"0".equals(no_read_msg) || !"0".equals(no_read_mail)) {
            ivRedPoint.setVisibility(View.VISIBLE);
        } else {
            ivRedPoint.setVisibility(View.GONE);
        }
    }

    private void setNewMsg(HomeFragmentInfo homeFragmentInfo) {
        List<HomeFragmentInfo.NoticeBean> msgList = homeFragmentInfo.getNotice();
        if (msgList != null && msgList.size() > 0) {
            llNewMsg.setVisibility(View.VISIBLE);
            if (msgList.size() == 1) {
                rlMsg1.setVisibility(View.VISIBLE);
                rlMsg2.setVisibility(View.GONE);

                tvMsg1.setText(msgList.get(0).getTitle());
                tvTime1.setText(msgList.get(0).getTime());

            } else if (msgList.size() == 2) {
                rlMsg1.setVisibility(View.VISIBLE);
                rlMsg2.setVisibility(View.VISIBLE);

                tvMsg1.setText(msgList.get(0).getTitle());
                tvTime1.setText(msgList.get(0).getTime());

                tvMsg2.setText(msgList.get(1).getTitle());
                tvTime2.setText(msgList.get(1).getTime());
            }
        } else {
            llNewMsg.setVisibility(View.GONE);
        }
    }

    private void setPaiHangData(HomeFragmentInfo homeFragmentInfo) {
        List<HomeFragmentInfo.TodayInfosBean> today_infos = homeFragmentInfo.getToday_infos();
        if (today_infos != null && today_infos.size() > 0) {
            llPaihang.setVisibility(View.VISIBLE);
            switch (today_infos.size()) {
                case 1:
                    rlPh1.setVisibility(View.VISIBLE);
                    rlPh1.setVisibility(View.GONE);
                    rlPh1.setVisibility(View.GONE);

                    getPhOne(today_infos);
                    break;
                case 2:
                    rlPh1.setVisibility(View.VISIBLE);
                    rlPh1.setVisibility(View.VISIBLE);
                    rlPh1.setVisibility(View.GONE);

                    getPhOne(today_infos);
                    getPhTwo(today_infos);
                    break;
                case 3:
                    rlPh1.setVisibility(View.VISIBLE);
                    rlPh1.setVisibility(View.VISIBLE);
                    rlPh1.setVisibility(View.VISIBLE);

                    getPhOne(today_infos);
                    getPhTwo(today_infos);
                    getPhThree(today_infos);
                    break;
            }
        } else {
            llPaihang.setVisibility(View.GONE);
        }
    }

    private void getPhThree(List<HomeFragmentInfo.TodayInfosBean> today_infos) {
        getPhTwo(today_infos);

        userImg2 = today_infos.get(2).getUser_img();
        phMobile2 = today_infos.get(2).getMobile();
        phRegionName2 = today_infos.get(2).getRegion_name();
        phOrderCount2 = today_infos.get(2).getOrder_count();
        phMobile2 = phMobile2.replace(phMobile2.substring(3, 7), "****");

        tvPhMobile3.setText(phMobile2);
        tvPhAddress3.setText(phRegionName2);
        tvPhNum3.setText(phOrderCount2 + "单");
        setPhPhoto(ivPhPhoto3, userImg2);
    }

    private void getPhTwo(List<HomeFragmentInfo.TodayInfosBean> today_infos) {
        getPhOne(today_infos);

        userImg1 = today_infos.get(1).getUser_img();
        phMobile1 = today_infos.get(1).getMobile();
        phRegionName1 = today_infos.get(1).getRegion_name();
        phOrderCount1 = today_infos.get(1).getOrder_count();
        phMobile1 = phMobile1.replace(phMobile1.substring(3, 7), "****");

        tvPhMobile2.setText(phMobile1);
        tvPhAddress2.setText(phRegionName1);
        tvPhNum2.setText(phOrderCount1 + "单");
        setPhPhoto(ivPhPhoto2, userImg1);

    }

    private void getPhOne(List<HomeFragmentInfo.TodayInfosBean> today_infos) {
        userImg = today_infos.get(0).getUser_img();
        phMobile = today_infos.get(0).getMobile();
        phRegionName = today_infos.get(0).getRegion_name();
        phOrderCount = today_infos.get(0).getOrder_count();
        phMobile = phMobile.replace(phMobile.substring(3, 7), "****");

        tvPhMobile1.setText(phMobile);
        tvPhAddress1.setText(phRegionName);
        tvPhNum1.setText(phOrderCount + "单");
        setPhPhoto(ivPhPhoto1, userImg);

    }

    private void setPhPhoto(ImageView iv, String urlImge) {
        // 加载圆形头像
        RequestOptions options = new RequestOptions().bitmapTransform(new CircleCrop());
        Glide.with(_mActivity)
                .load(urlImge)
                .apply(options)
                .into(iv);
    }

    private void saveSrValue(HomeFragmentInfo homeFragmentInfo) {
        String device_sn = homeFragmentInfo.getDevice_sn();
        if (device_sn != null && !TextUtils.isEmpty(device_sn)) {
            PrefReadCardTools.setString(_mActivity, ConstantsValue.SRDEVICESN, device_sn.trim()); // 保存森锐串码,读卡使用
        } else {
            PrefReadCardTools.setString(_mActivity, ConstantsValue.SRDEVICESN, ""); // 保存森锐串码,读卡使用
        }
    }

    private void setPhoto(HomeFragmentInfo homeFragmentInfo) {
        HomeFragmentInfo.UserInfoBean userInfo = homeFragmentInfo.getUser_info();
        String userName = userInfo.getUser_name();
        String mobile = userInfo.getMobile();

        tvAccount.setText(userName); //设置账号
        mobile = mobile.replace(mobile.substring(3, 7), "****");
        tvUserHone.setText(mobile); // 设置电话

        // 加载圆形头像
        RequestOptions options = new RequestOptions().bitmapTransform(new CircleCrop())
                .placeholder(R.mipmap.home_nomphoto) //图片加载出来前，显示的图片
                .fallback(R.mipmap.home_nomphoto)  //url为空的时候,显示的图片
                .error(R.mipmap.home_nomphoto); //图片加载失败后，显示的图片

        Glide.with(_mActivity)
                .load(userInfo.getImg())
                .apply(options)
                .into(ivUserPhoto);
    }

    private void setHomeButton(HomeFragmentInfo homeFragmentInfo) {
        isHaveData = true;
        List<HomeFragmentInfo.ActionListBean> action_list = homeFragmentInfo.getAction_list();
        mList = new ArrayList<>(); // 初始化集合
        if (action_list != null && action_list.size() > 0) {
            gvFunction.setVisibility(View.VISIBLE);
            mList.addAll(action_list);
            homeGrideAdapter.setData(mList, isHaveData);
        } else {
            ToastUtils.showShortToast(_mActivity, "获取功能数据失败");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0 && requestCode == REQUEST_CODE) {
            if (data != null) {
                Bundle str = data.getExtras();
                if (str != null) {
                    String result = str.getString(CodeUtils.RESULT_STRING);
                    int resultType = str.getInt(CodeUtils.RESULT_TYPE, CodeUtils.RESULT_FAILED);
                    switch (resultType) {
                        case CodeUtils.RESULT_SUCCESS:
                            Intent intent1 = new Intent(_mActivity, ZxingWebActivity.class);
                            if (result.contains("djlm.wang/Sale/Card/img/phone/")) {
                                intent1.putExtra("url_one", result);
                                intent1.setClass(_mActivity, ChooseActivity.class);
                                startActivity(intent1);
                            } else if (result.contains("djlm.wang/Sale/Card/duo_img/phone/")) {
                                intent1.putExtra("url_two", result);
                                intent1.setClass(_mActivity, ChooseActivity.class);
                                startActivity(intent1);
                            } else if (result.contains("djlm.wang/Sale/Card/camera/phone/")) {
                                intent1.putExtra("sucUrl", result);
                                intent1.setClass(_mActivity, DianXinActivity.class);
                                startActivity(intent1);
                            } else if (result.contains("App5/PhoneApi/up_order_user_sign")) {
                                ToastUtils.showShortToast(_mActivity, "读取二维码不符，请扫描正确内容");
//                                intent1.putExtra("SIGN_URL", result);
//                                intent1.setClass(_mActivity, QianMingActivity.class);
//                                startActivity(intent1);
                            } else {
                                ToastUtils.showShortToast(_mActivity, "读取二维码不符，请扫描正确内容");
                            }
                            break;
                        case CodeUtils.RESULT_FAILED:
                            ToastUtils.showShortToast(_mActivity, "扫描失败，请重新扫描2");
                            break;
                    }
                }
            }

        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

}
